﻿#include "NetWork.h"
#include <QDataStream>
#include <windows.h>
#include "eventtype.h"
#include <QCoreApplication>
#include <QDebug>
#include "debug.h"

TcpNetWork::TcpNetWork(QObject *parent /*= 0*/)
	:QThread(parent),m_quit(false)
{
	m_recver = parent;
}

TcpNetWork::~TcpNetWork()
{
	
}

void TcpNetWork::startWork(const QString &hostName, quint16 port)
{
	QMutexLocker locker(&m_mutex);
	m_port = port;
	m_host_name = hostName;
	if (!isRunning())
	{
		start();
	}
	else
	{
		m_cond.wakeOne();
	}
}

void TcpNetWork::run()
{
	m_mutex.lock();
	QString server_name = m_host_name;
	int port = m_port;
	m_mutex.unlock();

	const int timeout = 5 * 1000;

	m_os_tcp = new OS_TcpSocket();
	m_os_tcp->Open();
	
	if (m_os_tcp->Connect(OS_SockAddr(server_name.toStdString().c_str(), port))==-1)
	{
		NetEventPacket pkt;
		pkt.type = PktType_ConnectFail;
		emit ConnectServerFail(pkt);

		return;
	}

	char temp_buffer[TEM_BUFFER_SIZE];
	int recv_size = 0;  

	while (!m_quit)
	{
		//先处理发送事件 
		while(m_send_buff.size()>0)
		{
			m_mutex_send_buff.lock();
			TcpPkt pkt=m_send_buff.front();
			m_send_buff.pop_front();
			m_mutex_send_buff.unlock();

			Debug("发送数据包 \n");
			m_os_tcp->Send((const char *)pkt.header, 2);
			m_os_tcp->Send(pkt.buf, pkt.buf_len);
			Debug("发送完成 \n");
			delete []pkt.buf;
		}

		while (m_os_tcp->Select_ForReading(0)>0)
		{
			int recv_size=m_os_tcp->Recv(temp_buffer, TEM_BUFFER_SIZE);
			Debug("读取数据 recv_size : %d\n",recv_size);
			m_read_data_buffer.push_data_copy(temp_buffer, recv_size);
			Debug("加入读缓存\n");
			while (true)
			{
				int size = m_read_data_buffer.read_header(TCP_PKT_HERDER_SIZE);

				if (size < 0)
				{
					break;
				}
				else if (size > 0)
				{
					if (size >= 0x1000000)
					{

					}
					else
					{
						recv_forward(size);
						m_read_data_buffer.reset_databuffer();
					}

				}
			}
		}

		Sleep(500);

	}
}

void TcpNetWork::sendData(uint16_t pkt_type, char * data, uint16_t data_size)
{
	TcpPkt pkt(data_size,pkt_type,data);
	m_mutex_send_buff.lock();
	m_send_buff.push_back(pkt);
	m_mutex_send_buff.unlock();
}

void TcpNetWork::recv_forward(int buffer_size)
{
	char * tem = new char[buffer_size];
	this->m_read_data_buffer.read_data(tem, buffer_size);
	
	NetEventPacket pkt;
	pkt.data_size = buffer_size - 2;
	pkt.data = tem + 2;
	memcpy(&pkt.type, tem, 2);
	Debug("pkt_type : %d\n",pkt.type);
	emit recvData(pkt);
}
